# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

import datetime
import logging

from odoo import api, fields, models

_logger = logging.getLogger(__name__)

important_faults = ['客车', '人身', '防错办', '防撤溜']
handel_faults = ['问题牌(白牌)', '问题牌(黄牌)', '问题牌(红牌)', '问题牌(事故苗子)', '问题牌（黄牌）', '问题牌（红牌）', '问题牌（事故苗子）']


# 获取时间年月
def get_year_month(this_time):
    import datetime
    if this_time:
        if this_time == datetime.datetime:
            now_time = this_time
        else:
            now_time = datetime.datetime.strptime(this_time[:10], "%Y-%m-%d")
    return (now_time.year, now_time.month)


# 获取某月第一天和最后一天
def this_year_month(this_time=None, month=0):
    import time, datetime, calendar
    # 当前时间
    now_time = datetime.datetime.now()
    # 如果传入时间，使用传入时间
    if this_time:
        if type(this_time) == type(datetime.datetime.now()):
            now_time = this_time
        else:
            now_time = datetime.datetime.strptime(this_time[:10], "%Y-%m-%d")
    now_time_mk = time.mktime(now_time.timetuple())  # 当前时间戳
    if month < 0:
        if now_time.month <= abs(month):
            compute_date = "%s-%s-%s" % (now_time.year - 1, 12 + now_time.month + month, now_time.day)
            now_time = datetime.datetime.strptime(compute_date, "%Y-%m-%d")
        else:
            compute_date = "%s-%s-%s" % (now_time.year, now_time.month + month, now_time.day)
            now_time = datetime.datetime.strptime(compute_date, "%Y-%m-%d")
    if month > 0:
        if now_time.month + abs(month) > 12:
            compute_date = "%s-%s-%s" % (now_time.year + 1, now_time.month + month - 12, now_time.day)
            now_time = datetime.datetime.strptime(compute_date, "%Y-%m-%d")
        else:
            compute_date = "%s-%s-%s" % (now_time.year, now_time.month + month, now_time.day)
            now_time = datetime.datetime.strptime(compute_date, "%Y-%m-%d")

    # 本月第一天
    datetime.timedelta(days=31)
    last_day = calendar.monthrange(now_time.year, now_time.month)[1]
    first_time = datetime.datetime(now_time.year, now_time.month, 1).strftime("%Y-%m-%d %H:%M:%S")
    last_time = datetime.datetime(now_time.year, now_time.month, last_day, 23, 59, 59).strftime("%Y-%m-%d %H:%M:%S")

    return (first_time, last_time)


def multi_cont(l1, l2):
    set1 = set(l1)
    set2 = set(l2)
    if len(set1 & set2):
        return True
    else:
        return False


class CrEmpScore(models.Model):
    _name = "cr.emp.score"
    _description = "积分"

    name = fields.Char(string='姓名', related='staff_id.name', store=True)
    card_id = fields.Char(string='工号', related='staff_id.card_id', store=True)
    ws_id = fields.Many2one('cr.emp.workshop', string='所属车间', related='staff_id.ws_id', store=True)
    team_id = fields.Many2one("cr.emp.team", string='班组', related='staff_id.team_id', store=True)
    post_id = fields.Many2one("cr.emp.post", string='岗位', related='staff_id.post_id', store=True)
    staff_id = fields.Many2one('cr.emp.staff', string='员工')
    level = fields.Selection([('0', '优秀'), ('1', '合格'), ('2', '失信')], compute='_compute_level', string='评级', store=True)

    add_score = fields.Integer(string='奖励积分', compute='_compute_score', store=True, default=0)
    sub_score = fields.Integer(string='处罚积分', compute='_compute_score', store=True, default=0)
    total_score = fields.Integer(string='总积分', compute='_compute_score', store=True, default=100)
    add_score_detail_ids = fields.One2many('cr.emp.score.item', 'add_score_id', string='加分积分条目')
    sub_score_detail_ids = fields.One2many('cr.emp.score.item', 'sub_score_id', string='减分积分条目')

    is_lose = fields.Boolean(string='是否失信')
    self_num = fields.Integer(string='自我暴露')
    other_num = fields.Integer(string='他人指出')
    check_num = fields.Integer(string='检查发现')
    time = fields.Datetime(string='记录时间')
    year = fields.Char(string='年份', compute='_compute_time', store=True)
    month = fields.Char(string='月份', compute='_compute_time', store=True)

    @api.depends('time')
    def _compute_time(self):
        for i in self:
            i.year = i.time.year
            i.month = i.time.month

    @api.depends('total_score')
    def _compute_level(self):
        for record in self:
            if 90 <= record.total_score:
                record.level = '0'
            elif 60 <= record.total_score < 90:
                record.level = '1'
            elif 60 > record.total_score > 0:
                record.level = '2'

    @api.depends('add_score_detail_ids', 'sub_score_detail_ids')
    def _compute_score(self):
        _logger.info('计算分数')
        for record in self:
            if record.add_score_detail_ids:
                record.add_score = sum([i.add_score for i in record.add_score_detail_ids])
            if record.sub_score_detail_ids:
                record.sub_score = sum([i.sub_score for i in record.sub_score_detail_ids])
                record.self_num = sum(
                    [(1 if i.fault_nature_type == 'self' else 0) for i in record.sub_score_detail_ids])
                record.check_num = sum(
                    [(1 if i.fault_nature_type == 'check' else 0) for i in record.sub_score_detail_ids])
                record.other_num = sum(
                    [(1 if i.fault_nature_type == 'other' else 0) for i in record.sub_score_detail_ids])

            record.total_score = 100 + record.add_score + record.sub_score
            if record.total_score < 0:
                record.total_score = 0
            inspire = self.env['cr.emp.inspire'].search(
                [('staff_id.id', '=', record.staff_id.id), ('year', '=', record.year)])
            inspire.add_score = record.add_score
            inspire.sub_score = record.sub_score
            inspire.total_score = record.total_score

    # @api.model
    # def read(self):
    #     self._compute_score()
    #     self._compute_level()
    #     return super(CrEmpScore,self).read()


    @api.model
    def init_score(self):
        staffs = self.env['cr.emp.staff'].search([])
        for staff in staffs:
            staff.write({
                'is_tolerate': False,
                'is_correct': False,
                'is_warning': False,
                'is_lose': False
            })
        staff_ids = staffs.ids
        now = datetime.datetime.now()
        times = self.get_year_month(now)
        year = times[0]
        month = times[1]
        for staff_id in staff_ids:
            score = self.search([('staff_id', '=', staff_id), ('year', '=', str(year)), ('month', '=', str(month))])
            if not score:
                _logger.info('\n创建员工id为%s的积分记录：' % staff_id)
                score = self.create({
                    'time': now,
                    'staff_id': staff_id,
                    'year': now.year,
                    'month': now.month,
                    'self_num': 0,
                    'other_num': 0,
                    'check_num': 0,
                })
            inspire = self.env['cr.emp.inspire'].search([('staff_id', '=', staff_id), ('year', '=', str(year))])
            if not inspire:
                _logger.info('\n创建员工id为%s的考核记录：' % staff_id)
                self.env['cr.emp.inspire'].create({
                    'score_id': score['id'],
                    'staff_id': staff_id,
                    'year': now.year,
                    'month': now.month,
                    'sub_money':300,
                })
            warning = self.env['cr.emp.warning'].search([('staff_id', '=', staff_id), ('year', '=', str(year)), ('month', '=', str(month))])
            if not warning:
                _logger.info('\n创建员工id为%s的预警记录：' % staff_id)
                self.env['cr.emp.warning'].create({
                    'time': now,
                    'staff_id': staff_id,
                    'year': now.year,
                    'month': now.month
                })

    @api.model
    def init_promise(self):
        staffs = self.env['cr.emp.staff'].search([])
        staff_ids = staffs.ids
        now = datetime.datetime.now()
        for staff_id in staff_ids:
            promise = self.search([('staff_id', '=', staff_id)])
            if not promise:
                _logger.info('\n创建员工id为%s的承诺记录：' % staff_id)
                staff = self.env['cr.emp.staff'].search_read([('id','=',int(staff_id))])[0]
                self.env['cr.emp.promise'].create({
                    'staff_id': staff['id'],
                    # 'ws_id': staff['ws_id'],
                    # 'post_id': staff['post_id'],
                    # 'team_id': staff['team_id'],
                    # 'dep_id': staff['dep_id']
                })

    def get_year_month(self, this_time):
        now_time = this_time
        return (now_time.year, now_time.month)


class CrEmpScoreItem(models.Model):
    _name = "cr.emp.score.item"
    _description = "积分条目"

    name = fields.Char(string='姓名', related='staff_id.name', store=True)
    card_id = fields.Char(string='工号', related='staff_id.card_id', store=True)
    ws_id = fields.Many2one('cr.emp.workshop', string='所属车间', related='staff_id.ws_id', store=True)
    team_id = fields.Many2one("cr.emp.team", string='班组', related='staff_id.team_id', store=True)
    post_id = fields.Many2one("cr.emp.post", string='岗位', related='staff_id.post_id', store=True)
    staff_id = fields.Many2one('cr.emp.staff', string='员工')

    score_id = fields.Many2one('cr.emp.score', string='积分')
    sub_score_id = fields.Many2one('cr.emp.score', string='积分')
    add_score_id = fields.Many2one('cr.emp.score', string='积分')

    time = fields.Datetime(string='发生时间')

    is_important2 = fields.Boolean()
    fault_type_id = fields.Many2one('cr.emp.fault.type', string='问题分类')

    is_handel_fault = fields.Boolean(string='是否为问题牌', compute='_compute_nature_type', store=True)
    sub_score = fields.Integer(string='扣分')
    add_score = fields.Integer(string='加分')
    fault_nature_type = fields.Selection([
        ('self', '自我暴露'),
        ('other', '他人指出'),
        ('check', '检查发现')], string='问题性质类别')
    fault_nature_id = fields.Many2many('cr.emp.fault.nature', string='问题性质')
    survey = fields.Text(string='问题概况')

    is_test = fields.Boolean()
    is_test2 = fields.Boolean()
    is_lose2 = fields.Boolean()
    add_card_id = fields.Char(string='防控工号')
    add_staff_id = fields.Many2one('cr.emp.staff', string='员工', compute='_compute_add_staff', store=True)
    add_name = fields.Char(string='防控姓名', related='add_staff_id.name', store=True)
    observe_start_time = fields.Date(string='观察期起')
    observe_end_time = fields.Date(string='观察期止')
    observe_time = fields.Char(string='观察期止', compute='_compute_observe_time', store=True)
    detail = fields.Html(string='详情')
    year = fields.Char(string='年份', compute='_compute_time', store=True)
    month = fields.Char(string='月份', compute='_compute_time', store=True)

    @api.depends('time')
    def _compute_time(self):
        for i in self:
            i.year = i.time.year
            i.month = i.time.month

    def search_for_nature(self, id):
        id = int(id)
        record = self.search_read([('id', '=', id)])[0]
        natures = self.env['cr.emp.fault.nature'].search_read([('id', 'in', record['fault_nature_id'])])
        return [i['name'] for i in natures]

    @api.depends('fault_nature_id')
    def _compute_nature_type(self):
        for record in self:
            # record = self.search_read([('id','=',record.id)])[0]
            fault_natures = self.search_for_nature(record.id)
            times = record.search_count(
                [('staff_id', '=', record.staff_id.id), ('fault_type_id', '=', record.fault_type_id.id)])
            _logger.info('问题次数%s' % times)
            if record.fault_nature_id:
                record.fault_nature_type = record.env['cr.emp.fault.nature'].search(
                    [('id', '=', record.fault_nature_id[0].id)]).type

    @api.depends('add_card_id')
    def _compute_add_staff(self):
        for record in self:
            # lqy 增加加分人
            if record.add_card_id:
                record.add_staff_id = record.env['cr.emp.staff'].search([('card_id', '=', record.add_card_id)])

    @api.depends('observe_start_time', 'observe_end_time')
    def _compute_observe_time(self):
        # lqy 观察期字符'
        for record in self:
            if record.observe_start_time and record.observe_end_time:
                record.observe_time = record.observe_start_time.strftime(
                    '%Y-%m-%d') + '至' + record.observe_end_time.strftime(
                    '%Y-%m-%d')

    @api.model
    def write(self,values):
        create=False
        is_test=False
        is_test2=False
        is_lose2=False
        if 'create' in values.keys():
            create=values.pop('create')
        if 'is_test' in values.keys():
            is_test=True
        if 'is_test2' in values.keys():
            is_test2=True
        if 'is_lose2' in values.keys():
            is_lose2=True
        if len(values.keys())==1:
            create=True
        _logger.info('修改数据：：：：：：'+str(values.get('staff_id')))
        a=values.get('add_staff_id')
        id=self.id
        this_time = self.time
        _logger.info(str(this_time))
        year = this_time.year
        month = this_time.month
        if self.add_staff_id:
            _logger.info('数据'+str(self.add_staff_id.id))
            _logger.info(type(self.add_staff_id.id))
            _logger.info('数据1'+str(values))
            add_score = self.env['cr.emp.score'].search(
                [('staff_id', '=', self.add_staff_id.id), ('year', '=', year), ('month', '=', month)])
            add_score.write({'write_date':datetime.datetime.now()})
            _logger.info('数据2'+str(values))
            if len(add_score) > 0:
                add_score = add_score[0]
                values.update({'add_score_id': add_score.id})
        if a:
            values.update({'add_staff_id': int(a)})

        _logger.info('数据3'+str(values))
        a=super(CrEmpScoreItem, self).write(values)
        _logger.info('是否为新建'+str(create))
        if create or is_test or is_test2 or is_lose2:
            pass
        else:
            _logger.info('修改：：')
            #更新减分积分
            sub_score = self.env['cr.emp.score'].search([('staff_id', '=', int(self.staff_id.id)),
                                                     ('year', '=', str(self.year)),
                                                     ('month', '=', str(self.month))])
            sub_score._compute_score()
            sub_score._compute_time()
            # 更新加分积分
            add_score = self.env['cr.emp.score'].search([('staff_id', '=', int(self.add_staff_id.id)),
                                                     ('year', '=', str(self.year)),
                                                     ('month', '=', str(self.month))])
            if len(add_score)>0:
                add_score._compute_score()
                add_score._compute_time()

            is_tolerate = self.is_tolerate(values)
            is_correct = self.is_correct(values)
            if is_tolerate:
                self.is_test = True
            else:
                tol_num = self.env['cr.emp.score.item'].search_count([('staff_id', '=', int(self.add_staff_id.id)),
                                                                      ('year', '=', str(self.year)),
                                                                      ('month', '=', str(self.month)),
                                                                      ('is_test', '=', True)])
                _logger.info(str(tol_num))
                if tol_num == 1 and self.is_test == False:
                    _logger.info('删除容错')
                    self.env['cr.emp.tolerate'].search([('staff_id', '=', int(self.staff_id.id)),
                                                        ('year', '=', str(self.year)),
                                                        ('month', '=', str(self.month))]).unlink()
                self.is_test =False
            if is_correct == 1:
                _logger.info('设置该问题纠错')
                self.is_test2 = True
                self.staff_id.write(
                    {'observe_start_time': self.observe_start_time,
                     'observe_end_time': self.observe_end_time})
                _logger.info('人员设置纠错期%s' % str(self.observe_time))
                self.env['cr.emp.correct'].create({
                    'staff_id': self.staff_id.id,
                    'handle_num': 1,
                    'observe_time': self.observe_time,
                    'time': self.time
                })
                _logger.info('\n创建纠错记录 人员:%s 月份:%s' % (str(self.staff_id.id), str(self.month)))
            elif is_correct == 2:
                self.is_test2 = True
                ym = this_year_month(self.time)
                start_time = ym[0]
                end_time = ym[1]
                correct = self.env['cr.emp.correct'].search([('staff_id', '=', self.staff_id.id),
                                                             ('time', '>', start_time),
                                                             ('time', '<', end_time)])
                num1 = correct.handle_num + 1
                correct.write({'is_stop': True, 'handle_num': num1
                               })
                _logger.info('\n纠错记录更新：%s' % str({'中止': True, '牌数': num1}))
            else:
                cor_num = self.env['cr.emp.score.item'].search_count([('staff_id', '=', int(self.staff_id.id)),
                                                                      ('year', '=', str(self.year)),
                                                                      ('month', '=', str(self.month)),
                                                                      ('is_test2', '=', True)])
                if cor_num == 1 and self.is_test2 == False:
                    _logger.info('删除纠错')
                    self.env['cr.emp.correct'].search([('staff_id', '=', int(self.staff_id.id)),
                                                       ('year', '=', str(self.year)),
                                                       ('month', '=', str(self.month))]).unlink()
                _logger.info(str(cor_num))
                self.is_test2=False
            is_lose = self.is_lose(values)
            if is_lose:
                self.is_lose2=True
                sub_score.is_lose=True
                _logger.info('设置积分失信')

            else:
                help_num = self.env['cr.emp.score.item'].search_count([('staff_id', '=', int(self.staff_id.id)),
                                                                       ('year', '=', str(self.year)),
                                                                       ('month', '=', str(self.month)),
                                                                       ('is_lose2', '=', True)])
                if help_num == 1 and self.is_lose2 == False:
                    _logger.info('删除帮促')
                    self.env['cr.emp.help'].search([('staff_id', '=', int(self.staff_id.id)),
                                                    ('year', '=', str(self.year)),
                                                    ('month', '=', str(self.month))]).unlink()
                _logger.info(str(help_num))
                self.is_lose2 =False
                sub_score.is_lose=False
        return a



    @api.model
    def create(self, values):
        _logger.info('创建积分条目by：' + str(values))
        is_tolerate = self.is_tolerate(values)
        is_correct = self.is_correct(values)
        score_item = super(CrEmpScoreItem, self).create(values)
        _logger.info('问题分数' + str(score_item.sub_score))
        staff_id = self.env['cr.emp.staff'].search([('id', '=', int(values.get('staff_id')))])
        if is_tolerate:
            _logger.info('设置该问题容错')
            score_item.is_test = True

        if is_correct == 1:
            _logger.info('设置该问题纠错')
            score_item.is_test2 = True
            staff_id.write(
                {'observe_start_time': score_item.observe_start_time, 'observe_end_time': score_item.observe_end_time})
            _logger.info('人员设置纠错期%s' % str(score_item.observe_time))
            self.env['cr.emp.correct'].create({
                'staff_id': score_item.staff_id.id,
                'handle_num': 1,
                'observe_time': score_item.observe_time,
                'time': score_item.time
            })
            _logger.info('\n创建纠错记录 人员:%s 月份:%s' % (str(staff_id.id), str(score_item.month)))
        elif is_correct == 2:
            score_item.is_test2=True
            ym = this_year_month(score_item.time)
            start_time = ym[0]
            end_time = ym[1]
            correct = self.env['cr.emp.correct'].search([('staff_id', '=', staff_id.id),
                                                         ('time', '>', start_time),
                                                         ('time', '<', end_time)])
            num1 = correct.handle_num + 1
            correct.write({'is_stop': True, 'handle_num': num1
                           })
            _logger.info('\n纠错记录更新：%s' % str({'中止': True, '牌数': num1}))
        else:
            _logger.info('\n###问题不纠错')
            pass
        is_lose = self.is_lose(values)
        if is_lose:
            _logger.info('设置该问题失信')
            score_item.write({'is_lose2': True})
        this_time=values.get('time')
        year=get_year_month(this_time)[0]
        month=get_year_month(this_time)[1]
        sub_score = self.env['cr.emp.score'].search([('staff_id', '=', score_item.staff_id.id),('year','=',year),('month','=',month)])
        if len(sub_score)>0:
            sub_score=sub_score[0]
            if is_lose:
                sub_score.write({'is_lose':True})
        score_item.write({'sub_score_id': sub_score.id,'create':True})
        if score_item.add_card_id:
            add_score = self.env['cr.emp.score'].search([('staff_id', '=', score_item.add_staff_id.id),('year','=',year),('month','=',month)])
            if len(add_score) > 0:
                add_score = add_score[0]
            # score_item.write({'sub_score_id': sub_score.id,create：True})
                score_item.write({'add_score_id': add_score.id,'create':True})
        _logger.info('问题分数end' + str(score_item.sub_score))
        return score_item

    # 是否在纠错期内
    def is_in_observe(self, staff_id, this_time):
        _logger.info('员工'+str(staff_id)+str(this_time))
        staff = self.env['cr.emp.staff'].search([('id', '=', int(staff_id)),
                                                 ('observe_start_time', '<', this_time),
                                                 ('observe_end_time', '>', this_time)])
        if staff:
            _logger.info('\n员工在纠错期内')
            return True
        else:
            _logger.info('\n员工不在纠错期内')
            return False

    # 是否容错判断
    def is_tolerate(self, values):
        _logger.info('\n####问题容错判断：')
        staff_id = values.get('staff_id')
        this_time = values.get('time')
        ym = get_year_month(this_time)
        year = ym[0]
        month = ym[1]
        important = self.is_important(values)
        handle = self.is_handle(values)
        if handle:
            handle_nums = self.handle_nums(values.get('staff_id'), values.get('time'))
            if not important and handle_nums == 0:
                _logger.info('\n####该问题容错')
                tolerate = self.env['cr.emp.tolerate'].search(
                    [('staff_id', '=', staff_id), ('year', '=', str(year)), ('month', '=', str(month))])
                if len(tolerate) == 0:
                    _logger.info('\n创建容错记录 人员:%s 月份:%s' % (str(staff_id), str(this_time)))
                    fault_nature_type = self.env['cr.emp.fault.nature'].search(
                        [('id', '=', values.get('fault_nature_id')[0])]).type
                    self.env['cr.emp.tolerate'].create({
                        'staff_id': staff_id,
                        'fault_type_id': values.get('fault_type_id'),
                        'fault_nature_type': fault_nature_type,
                        'fault_nature_id': values.get('fault_nature_id'),
                        'time': datetime.datetime.strptime(this_time,"%Y-%m-%d %H:%M:%S")
                    })
                    return True
                else:
                    _logger.info('\n已有容错记录')
                    return True
            else:
                _logger.info('\n####该问题不容错')
                return False
        else:
            _logger.info('\n####该问题发牌问题，不容错')
            return False

    # 纠错和中止
    def is_correct(self, values):
        _logger.info('\n####问题纠错判断：')
        observe = self.is_in_observe(values.get('staff_id'), values.get('time'))
        _logger.info('\n####问题人员是否在观察期：%s' % str(observe))
        handle = self.is_handle(values)
        _logger.info('\n####问题是否为发牌问题：%s' % str(handle))
        important = self.is_important(values)
        _logger.info('\n####问题是否为重要问题：%s' % str(important))
        if not handle:
            _logger.info('\n####问题非发牌问题')
            return 0
        if not handle and not important:
            _logger.info('\n####问题非纠错问题')
            if observe:
                lower_score = self.lower_90(int(values.get('staff_id')), values.get('time'))
                score = lower_score + int(values.get('sub_score'))
                _logger.info('\n##########纠错期内问题后分数：%s' % score)
                if lower_score <90:
                    _logger.info('\n####该纠错问题中止')
                    return 2
            return 0
        second_handle = False
        handle_num = self.handle_nums(values.get('staff_id'), values.get('time'))

        if not observe:
            if handle and handle_num == 1:
                _logger.info('\n####该问题为当月第二张牌，纠错')
                second_handle = True
                return 1
            elif important and self.important_nums(values.get('staff_id'), values.get('time')) == 0:
                _logger.info('\n####该问题为当月第一个重要问题，纠错')
                return 1
            else:

                _logger.info('\n####该问题不纠错')
                return 0
        else:
            _logger.info('\n##########纠错期内')
            lower_score = self.lower_90(int(values.get('staff_id')), values.get('time'))
            score = lower_score + int(values.get('sub_score'))
            _logger.info('\n##########纠错期内问题后分数：%s'%score)
            if lower_score < 90 or handle or important:
                _logger.info('\n####该纠错问题中止')
                return 2
            else:
                return 0

    # 失信
    def is_lose(self, values):
        _logger.info('\n####开始失信判断')
        staff_id = values.get('staff_id')
        this_time = values.get('time')
        ym = get_year_month(this_time)
        year = ym[0]
        month = ym[1]
        _logger.info('\n####员工信息:%s,%s,%s,%s' % (str(staff_id), str(this_time), str(year), str(month)))

        fault_nature_ids = self.env['cr.emp.fault.nature'].search([('id', 'in', values.get('fault_nature_id'))]).read()
        fault_natures = [i['name'] for i in fault_nature_ids]
        _logger.info('\n####问题性质：%s' % str(fault_natures))
        score = self.env['cr.emp.score'].search([('staff_id', '=', staff_id),
                                                 ('year', '=', str(year)),
                                                 ('month', '=', str(month))]).total_score
        score=score+int(values.get('sub_score'))
        if '重复违反承诺' in fault_natures:
            _logger.info('\n####因重复违反承诺，失信')
        elif score < 60:
            _logger.info('\n####因分数%s小于60，失信' % score)
        else:
            _logger.info('\n####非失信问题')
            return False
        help_num = self.env['cr.emp.help'].search_count([('staff_id', '=', staff_id),
                                                         ('year', '=', str(year)),
                                                         ('month', '=', str(month))])
        _logger.info('\n####已有帮促记录%s条' % help_num)
        if help_num == 0:
            _logger.info('\n####创建失信记录staff_id:%s' % str(staff_id))
            self.env['cr.emp.help'].create({
                'staff_id': staff_id,
                'time': this_time
            })
            return True
        else:
            _logger.info('\n####已有失信记录')
            return False

    def is_important(self, values):
        _logger.info(values.get('fault_type_id'))
        import_faults = self.env['cr.emp.fault.type'].search([('name','in',important_faults)])
        _logger.info(import_faults.ids)
        fault_type_id = int(values.get('fault_type_id'))
        if fault_type_id in import_faults.ids:
            _logger.info('\n####该问题为重要问题')
            return True
        return False

    def is_handle(self, values):
        fault_nature_ids = values.get('fault_nature_id')
        handel_faults_ids = self.env['cr.emp.fault.nature'].search([('name','like','问题牌')])
        _logger.info(handel_faults_ids.ids)
        for i in fault_nature_ids:
            if int(i) in [int(j) for j in handel_faults_ids.ids]:
                _logger.info('\n####问题为发牌问题')
                return True
        _logger.info('\n####问题非发牌问题')
        return False

    # 判断当月是否有发牌
    def handle_nums(self, staff_id, this_time):
        times = this_year_month(this_time)
        first_time = times[0]
        last_time = times[1]
        _logger.info('员工，时间'+str(staff_id)+str(first_time)+str(last_time))
        handel_faults_ids = self.env['cr.emp.fault.nature'].search([('name','like','问题牌')])
        faults = self.search(
            [('staff_id', '=', int(staff_id)), ('time', '<', last_time), ('time', '>', first_time)])
        num = 0
        for i in faults:
            flag = False
            for j in i.fault_nature_id:
                if int(j) in handel_faults_ids.ids:
                    flag = True
            if flag == True:
                num += 1
        _logger.info('\n####已有发牌问题%s条' % num)
        return num

    # 判断是否是当月是否有重要牌
    def important_nums(self, staff_id, this_time):
        times = this_year_month(this_time)
        first_time = times[0]
        last_time = times[1]
        faults = self.env['cr.emp.score.item'].search(
            [('staff_id', '=', staff_id), ('time', '<', last_time), ('time', '>', first_time)])
        num = 0
        for i in faults:
            flag = False
            for j in i.fault_nature_id.ids:
                if j in [1, 2, 3, 4, '1', '2', '3', '4']:
                    flag = True
            if flag == True:
                num += 1
        _logger.info('\n####已有中重要问题%s条' % num)
        return num

    # 小于90分
    def lower_90(self, staff_id, this_time):
        ym = get_year_month(this_time)
        year = ym[0]
        month = ym[1]
        score = self.env['cr.emp.score'].search([('staff_id', '=', staff_id),
                                                 ('year', '=', str(year)),
                                                 ('month', '=', str(month))]).total_score
        return score

    def lower_60(self, staff_id, this_time):
        ym = get_year_month(this_time)
        year = ym[0]
        month = ym[1]
        score = self.env['cr.emp.score'].search([('staff_id', '=', staff_id),
                                                 ('year', '=', str(year)),
                                                 ('month', '=', str(month))]).total_score
        _logger.info('\n####员工当前分数%s' % score)

        if score < 60:
            _logger.info('\n####员工分数小于60分')
            return True
        else:
            return False

    def is_hg(self, staff_id, this_time):
        year1 = get_year_month(this_time)[0]
        month1 = get_year_month(this_time)[1]
        time2 = this_year_month(this_time, -1)[0]
        year2 = get_year_month(time2)[0]
        month2 = get_year_month(time2)[1]
        # 可以优化
        score1 = self.env['cr.emp.score'].search([('staff_id', '=', staff_id),
                                                  ('year', '=', str(year1)),
                                                  ('month', 'in', str(month1))]).total_score

        score2 = self.env['cr.emp.score'].search([('staff_id', '=', staff_id),
                                                  ('year', '=', str(year2)),
                                                  ('month', '=', str(month2))]).total_score
        if 60 <= score1 < 90 and 60 <= score2 < 90:
            _logger.info('\n员工连续两月成绩为合格')
            return True
        else:
            return False

    @api.model
    def unlink(self):
        _logger.info('进入删除')
        #级联删除减分数据
        sub_score = self.env['cr.emp.score'].search([('staff_id', '=', int(self.staff_id.id)),
                                                 ('year', '=', str(self.year)),
                                                 ('month', '=', str(self.month))])
        if len(sub_score)>0:
            old_sub_ids=sub_score.sub_score_detail_ids.ids
            _logger.info('旧减分'+str(old_sub_ids)+'Id'+str(self.id))
            if self.id in old_sub_ids:
                old_sub_ids.remove(self.id)
                new_sub_ids=old_sub_ids
                if new_sub_ids==[]:
                    new_sub_ids=[0]
                _logger.info('新减分'+str(new_sub_ids))
                sub_score.write({'sub_score_detail_ids':new_sub_ids})
                _logger.info('旧减分'+str(old_sub_ids)+'新减分'+str(new_sub_ids))
                #sub_score._compute_score()
                # _logger.info('最终减分'+str(sub_score.read().get('sub_score_detail_ids')))

        #级联删除加分数据
        add_score = self.env['cr.emp.score'].search([('staff_id', '=', int(self.add_staff_id.id)),
                                                 ('year', '=', str(self.year)),
                                                 ('month', '=', str(self.month))])
        if len(add_score)>0:
            old_add_ids=add_score.add_score_detail_ids.ids
            _logger.info('旧加分'+str(old_add_ids))
            if self.id in old_add_ids:
                old_add_ids.remove(self.id)
                new_add_ids = old_add_ids
                _logger.info('新减分'+str(new_sub_ids))
                add_score.write({'add_score_detail_ids':new_add_ids})
                _logger.info('旧加分'+str(old_add_ids)+'新减分'+str(new_sub_ids))
        #删除容错
        tol_num = self.env['cr.emp.score.item'].search_count([('staff_id', '=', int(self.add_staff_id.id)),
                                                 ('year', '=', str(self.year)),
                                                 ('month', '=', str(self.month)),('is_test','=',True)])
        _logger.info(str(tol_num))
        if tol_num==1 and self.is_test == True:
            _logger.info('删除容错')
            self.env['cr.emp.tolerate'].search([('staff_id', '=', int(self.staff_id.id)),
                                                 ('year', '=', str(self.year)),
                                                 ('month', '=', str(self.month))]).unlink()
        #删除纠错

        cor_num = self.env['cr.emp.score.item'].search_count([('staff_id', '=', int(self.staff_id.id)),
                                                 ('year', '=', str(self.year)),
                                                 ('month', '=', str(self.month)),('is_test2','=',True)])
        if cor_num==1 and self.is_test2 == True:
            _logger.info('删除纠错')
            self.env['cr.emp.correct'].search([('staff_id', '=', int(self.staff_id.id)),
                                                 ('year', '=', str(self.year)),
                                                 ('month', '=', str(self.month))]).unlink()
        _logger.info(str(cor_num))
        # 删除帮促

        help_num = self.env['cr.emp.score.item'].search_count([('staff_id', '=', int(self.staff_id.id)),
                                                              ('year', '=', str(self.year)),
                                                              ('month', '=', str(self.month)), ('is_lose2', '=', True)])
        if help_num == 1 and self.is_lose2 == True:
            _logger.info('删除帮促')
            sub_score.is_lose=False
            self.env['cr.emp.help'].search([('staff_id', '=', int(self.staff_id.id)),
                                               ('year', '=', str(self.year)),
                                               ('month', '=', str(self.month))]).unlink()
        _logger.info(str(help_num))

        return super(CrEmpScoreItem,self).unlink()